package com.fs.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.base.service.AbstractBaseEntityService;
import com.fs.common.exception.AppException;
import com.fs.iot.bean.dto.DeviceModelDTO;
import com.fs.iot.bean.query.DeviceModelQuery;
import com.fs.iot.domain.entity.DeviceModelEntity;
import com.fs.iot.domain.mapper.DeviceModelMapper;
import com.fs.iot.service.DeviceModelEntityService;
import com.fs.common.ErrorCodes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 设备模型服务实现 
 * @author Coder Generator 2025-03-22 15:13:29 
 **/
@Service
public class DeviceModelEntityServiceImpl extends AbstractBaseEntityService<DeviceModelEntity, DeviceModelDTO, DeviceModelMapper, DeviceModelQuery> implements DeviceModelEntityService {
    @Override
    protected QueryWrapper<DeviceModelEntity> queryToWrapper(DeviceModelQuery query) {
        return this.createQueryWrapper()
                .eq(StringUtils.isNotBlank(query.getId()), "id", query.getId())
                .in(null != query.getIds(), "id", query.getIds())
                .eq(StringUtils.isNotBlank(query.getCode()), "code", query.getCode())
                .eq(StringUtils.isNotBlank(query.getName()), "name", query.getName())
                .eq(StringUtils.isNotBlank(query.getCategoryId()), "category_id", query.getCategoryId())
                .orderByDesc("create_time");
    }

    /**
     * 插入前处理
     * 可以执行相关参数校验，校验不通过时抛出异常
     *
     * @return false时不进行插入，true时进行插入
     */
    @Override
    protected boolean processBeforeInsert(DeviceModelDTO dto) {
        // 检查设备编号是否重复
        String code = dto.getCode();
        if (StringUtils.isNotBlank(code)) {
            List<DeviceModelDTO> list = this.queryBuilder()
                    .eq("code", code)
                    .query();
            if (!list.isEmpty()) {
                throw AppException.of(ErrorCodes.IOT_MODEL_CODE_DUPLICATED);
            }
        }

        return super.processBeforeInsert(dto);
    }

    /**
     * 更新前处理
     *
     * @return false时不再进行更新，true时进行更新
     */
    @Override
    protected boolean processBeforeUpdate(DeviceModelDTO dto) {
        String code = dto.getCode();
        if (StringUtils.isNotBlank(code)) {
            List<DeviceModelDTO> list = this.queryBuilder().eq("code", code).neq("id", dto.getId()).query();
            if (!list.isEmpty()) {
                throw AppException.of(ErrorCodes.IOT_MODEL_CODE_DUPLICATED);
            }
        }

        return super.processBeforeUpdate(dto);
    }


}